//
//  CustomKeyBoardTextField.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/3/4.
//

import Foundation
import UIKit
import SwiftUI
import ETKeyboard

struct CustomKeyBoardTextField: UIViewRepresentable {
    @Binding var text: String
    /// 确认回调
    var returnKeyBlock: () -> Void
    /// 特殊按键回调
    var specialKeyBlock: (_ type: ETKeyboardButtonType) -> Void
        
    func makeUIView(context: Context) -> UITextField {
        let keyboard = ETKeyboardView(type: .customNumber1)
        keyboard.systemSoundId = 1103
        keyboard.returnKeyBlock = {
            returnKeyBlock()
        }
        keyboard.specialKeyBlock = { type in
            specialKeyBlock(type)
        }
        
        let textField = UITextField(frame: .zero)
        textField.inputView = keyboard
        textField.delegate = context.coordinator
        textField.becomeFirstResponder()
        return textField
    }
        
    //From SwiftUI To UIKit
    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
    }
    
    //From UIKit to SwiftUI
    func makeCoordinator() -> Coordinator{
        return Coordinator($text)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        @Binding var text: String
        
        init(_ text: Binding<String>) {
            self._text = text
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            DispatchQueue.main.async {
                self.text = textField.text ?? ""
            }
        }
    }
}
